<template>
	<view>
		<simple-toolbar :title="$t('pool.coinPool.newCoin')">
			<view class="returnToConfirm">
				<el-button @click="navBack">{{ $t('pool.coinPool.return') }}</el-button>
				<el-button @click="confirm" type="primary" :disabled="success">{{ $t('pool.coinPool.confirm') }}</el-button>
			</view>
		</simple-toolbar>

		<view class="pad-base form">
			<el-form :model="formData" :rules="rules" ref="formData" label-position="top">
				<el-form-item :label="$t('wallet.editWallet.coin')" prop="coin_name">
					<el-input v-model="formData.coin_name" :placeholder="$t('wallet.editWallet.coin_pla')"></el-input>
				</el-form-item>
			</el-form>
		</view>
	</view>
</template>

<script>
	import {
		getCoinList
	} from "../../../js_sdk/uni-admin/wallet.js"

	export default {
		onLoad(option) {
			// this.coinList = uni.getStorageSync('coinList')
			this.state = option.state
			if (this.state == 1) return
			let data = JSON.parse(decodeURIComponent(option.data));
			this.formData = data
			this.loadData()
		},
		data() {
			return {
				state: '',
				coinList: [],
				success: false,
				formData: {
					coin_name: '',
				},
				rules: {
					coin_name: [{
						required: true,
						validator: (rule, value, callback) => {
							let coin = this.formData.coin_name
							for (let item of this.coinList) {
								if (item.coin_name === coin) {
									callback(new Error(this.$t('pool.coinPool.repetition_pla')))
									return
								}
							}
							if (value === '') {
								callback(new Error(this.$t('wallet.editWallet.coin_pla')))
							} else {
								callback()
							}
						},
						trigger: 'blur'
					}],
				}
			}
		},
		methods: {
			async loadData() {
				try{
					let res = await getCoinList()
					this.coinList = res.data
				}catch(e){
					console.error(e)
				}
			},
			confirm() {
				this.$refs.formData.validate(async valid => {
					if (!valid) return
					if (this.state == 1) {
						delete this.formData.id
						await getCoinList('post', this.formData)
					} else {
						await getCoinList('put', this.formData)
					}
					await getCoinList('get', {showLoading: false}).then(res => {
						uni.setStorageSync('coinList', res.data)
					})
					this.success = true
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				});
			},
			navBack() {
				uni.navigateBack()
			}
		},
	}
</script>

<style scoped>
	/deep/ .el-select {
		width: 100%;
	}
</style>